/**************************************************
 * Filename: ConnectionProxy.java
 * Version: v1.0
 * CreatedDate: 2011-5-5
 * Copyright (C) 2011 By cafebabe.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 *
 * If you would like to negotiate alternate licensing terms, you may do
 * so by contacting the author: talentyao@foxmail.com
 ***************************************************/

package com.ywh.dbpools;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 数据库连接的代理类
 * <p>
 * 
 * 功能描述 能自动判断是否到期，已对Connection接口的close发方法进行代理
 * <p>
 * 
 * @author cafebabe
 * @since 2011-5-5
 * @version 1.0
 */
public class ConnectionProxy implements InvocationHandler, Delayed {
	private static long allowFreeTimes = 10 * 60 * 1000; // 允许连接空闲的时间

	private Connection conn; // 物理连接

	private boolean isUsing; // 是否正在被使用标志

	private long lastUseTime; // 最近一次开始使用时间

	public ConnectionProxy(Connection conn, long allowFreeTimes) {
		this.conn = conn;
		this.isUsing = false;
		ConnectionProxy.allowFreeTimes = allowFreeTimes;
		this.lastUseTime = System.currentTimeMillis();
	}

	/**
	 * 功能描述 创建Connection接口的代理
	 * 
	 * @return
	 */
	public Connection getConn() {
		Class<?>[] cls = conn.getClass().getInterfaces();
		if (cls.length == 0) {
			cls = new Class[] { Connection.class };
		}
		setUsing(true);
		setLastUseTime(System.currentTimeMillis() + 10 * 60 * 1000);
		return (Connection) Proxy.newProxyInstance(conn.getClass()
				.getClassLoader(), cls, this);
	}

	public boolean isUsing() {
		return isUsing;
	}

	public void setUsing(boolean isUsing) {
		this.isUsing = isUsing;
	}

	public long getLastUseTime() {
		return lastUseTime;
	}

	protected void setLastUseTime(long lastUseTime) {
		this.lastUseTime = lastUseTime;
	}

	/**
	 * 功能描述 真正关闭数据库连接的方法
	 * <p>
	 * 
	 * @throws SQLException
	 */
	protected void close() throws SQLException {
		conn.close();
		// conn = null;
	}

	/**
	 * 对close方法进行代理
	 * <p>
	 * override 方法
	 * 
	 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
	 *      java.lang.reflect.Method, java.lang.Object[])
	 */
	public Object invoke(Object obj, Method m, Object[] args) throws Throwable {
		// System.out.println("Obj:" + obj.getClass().getName());
		// System.out.println("Method：" + m.getName());
		if ("close".equals(m.getName())) {
			setUsing(false);
			setLastUseTime(System.currentTimeMillis());
			System.err.println("@@@@" + m.getName());
		} else {
			return m.invoke(conn, args);
		}
		return null;
	}

	public long getDelay(TimeUnit arg0) {
		return lastUseTime + allowFreeTimes - System.currentTimeMillis();
	}

	public int compareTo(Delayed d) {
		ConnectionProxy conProxy = (ConnectionProxy) d;
		return (int) (this.getLastUseTime() - conProxy.getLastUseTime());
	}

	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://192.168.1.217:3306/wulin", "root", "yaowenhao");
		System.out.println(conn);
		ConnectionProxy cp = new ConnectionProxy(conn, 3000);
		System.out.println("是否使用：" + cp.isUsing());
		Connection conn2 = cp.getConn();
		System.out.println("是否使用：" + cp.isUsing());
		if (conn2 == null) {
			System.out.println("为空！");
		}
		conn2.prepareStatement("");
		conn2.close();
		System.out.println("是否使用：" + cp.isUsing());
		System.out.println(conn);
		conn.prepareStatement("");
		try {
			conn.close();
			// conn.prepareStatement("");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(conn);
	}
}
